import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { 
  BarChart3, 
  TrendingUp, 
  Users, 
  BookOpen,
  GraduationCap,
  Calendar,
  Download,
  Filter,
  PieChart,
  Activity
} from 'lucide-react';

interface StatisticsData {
  label: string;
  value: number;
  change: number;
  trend: 'up' | 'down' | 'stable';
}

export function SystemStatistics() {
  const [selectedPeriod, setSelectedPeriod] = useState('semester');
  const [selectedDepartment, setSelectedDepartment] = useState('all');

  const overviewStats: StatisticsData[] = [
    {
      label: '学生总数',
      value: 12485,
      change: 2.5,
      trend: 'up'
    },
    {
      label: '教师总数',
      value: 856,
      change: 1.2,
      trend: 'up'
    },
    {
      label: '课程总数',
      value: 2341,
      change: 0.8,
      trend: 'up'
    },
    {
      label: '选课记录',
      value: 45672,
      change: 15.3,
      trend: 'up'
    }
  ];

  const enrollmentTrend = [
    { semester: '2021-1', students: 10250, courses: 1890 },
    { semester: '2021-2', students: 10580, courses: 1920 },
    { semester: '2022-1', students: 11200, courses: 2100 },
    { semester: '2022-2', students: 11650, courses: 2180 },
    { semester: '2023-1', students: 12100, courses: 2250 },
    { semester: '2023-2', students: 12350, courses: 2300 },
    { semester: '2024-1', students: 12485, courses: 2341 }
  ];

  const departmentStats = [
    {
      name: '计算机科学学院',
      students: 3245,
      teachers: 156,
      courses: 342,
      avgScore: 86.5,
      attendanceRate: 95.2
    },
    {
      name: '数学学院',
      students: 2158,
      teachers: 98,
      courses: 189,
      avgScore: 88.7,
      attendanceRate: 97.8
    },
    {
      name: '外语学院',
      students: 1876,
      teachers: 124,
      courses: 215,
      avgScore: 85.3,
      attendanceRate: 94.1
    },
    {
      name: '物理学院',
      students: 1654,
      teachers: 87,
      courses: 156,
      avgScore: 87.2,
      attendanceRate: 96.5
    },
    {
      name: '化学学院',
      students: 1432,
      teachers: 76,
      courses: 134,
      avgScore: 86.8,
      attendanceRate: 95.8
    }
  ];

  const gradeDistribution = [
    { grade: 'A', count: 5632, percentage: 28.5 },
    { grade: 'B', count: 7845, percentage: 39.7 },
    { grade: 'C', count: 4567, percentage: 23.1 },
    { grade: 'D', count: 1234, percentage: 6.2 },
    { grade: 'F', count: 498, percentage: 2.5 }
  ];

  const getTrendIcon = (trend: string) => {
    switch (trend) {
      case 'up':
        return <TrendingUp className="h-4 w-4 text-green-500" />;
      case 'down':
        return <TrendingUp className="h-4 w-4 text-red-500 rotate-180" />;
      default:
        return <Activity className="h-4 w-4 text-gray-500" />;
    }
  };

  const getTrendColor = (trend: string) => {
    switch (trend) {
      case 'up':
        return 'text-green-600';
      case 'down':
        return 'text-red-600';
      default:
        return 'text-gray-600';
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-medium">数据统计</h1>
        <div className="flex gap-2">
          <Button variant="outline">
            <Filter className="mr-2 h-4 w-4" />
            高级筛选
          </Button>
          <Button variant="outline">
            <Download className="mr-2 h-4 w-4" />
            导出报告
          </Button>
        </div>
      </div>

      {/* Filter Controls */}
      <Card>
        <CardContent className="p-4">
          <div className="flex gap-4 items-center">
            <div className="flex gap-2 items-center">
              <label className="text-sm font-medium">统计周期:</label>
              <Select value={selectedPeriod} onValueChange={setSelectedPeriod}>
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="week">本周</SelectItem>
                  <SelectItem value="month">本月</SelectItem>
                  <SelectItem value="semester">本学期</SelectItem>
                  <SelectItem value="year">本年度</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <div className="flex gap-2 items-center">
              <label className="text-sm font-medium">院系:</label>
              <Select value={selectedDepartment} onValueChange={setSelectedDepartment}>
                <SelectTrigger className="w-40">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部院系</SelectItem>
                  <SelectItem value="computer">计算机科学学院</SelectItem>
                  <SelectItem value="math">数学学院</SelectItem>
                  <SelectItem value="foreign">外语学院</SelectItem>
                  <SelectItem value="physics">物理学院</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">总览统计</TabsTrigger>
          <TabsTrigger value="enrollment">招生趋势</TabsTrigger>
          <TabsTrigger value="academic">学术统计</TabsTrigger>
          <TabsTrigger value="department">院系对比</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          {/* Overview Cards */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {overviewStats.map((stat, index) => (
              <Card key={index}>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-muted-foreground">{stat.label}</p>
                      <p className="text-2xl font-medium">{stat.value.toLocaleString()}</p>
                      <div className={`flex items-center text-sm ${getTrendColor(stat.trend)} mt-1`}>
                        {getTrendIcon(stat.trend)}
                        <span className="ml-1">{stat.change > 0 ? '+' : ''}{stat.change}%</span>
                        <span className="ml-2 text-muted-foreground">较上期</span>
                      </div>
                    </div>
                    <div className="text-right">
                      {index === 0 && <Users className="h-8 w-8 text-blue-500" />}
                      {index === 1 && <GraduationCap className="h-8 w-8 text-green-500" />}
                      {index === 2 && <BookOpen className="h-8 w-8 text-orange-500" />}
                      {index === 3 && <BarChart3 className="h-8 w-8 text-purple-500" />}
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* Quick Metrics */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center">
                  <PieChart className="mr-2 h-5 w-5" />
                  学生分布概况
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex justify-between items-center">
                    <span>本科生</span>
                    <div className="flex items-center gap-2">
                      <div className="w-20 bg-gray-200 rounded-full h-2">
                        <div className="bg-blue-600 h-2 rounded-full" style={{ width: '75%' }}></div>
                      </div>
                      <span className="text-sm">9,364 (75%)</span>
                    </div>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span>研究生</span>
                    <div className="flex items-center gap-2">
                      <div className="w-20 bg-gray-200 rounded-full h-2">
                        <div className="bg-green-600 h-2 rounded-full" style={{ width: '20%' }}></div>
                      </div>
                      <span className="text-sm">2,497 (20%)</span>
                    </div>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span>博士生</span>
                    <div className="flex items-center gap-2">
                      <div className="w-20 bg-gray-200 rounded-full h-2">
                        <div className="bg-orange-600 h-2 rounded-full" style={{ width: '5%' }}></div>
                      </div>
                      <span className="text-sm">624 (5%)</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center">
                  <BarChart3 className="mr-2 h-5 w-5" />
                  课程统计
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex justify-between items-center">
                    <span>必修课程</span>
                    <div className="flex items-center gap-2">
                      <Badge>1,405门</Badge>
                      <span className="text-sm text-muted-foreground">(60%)</span>
                    </div>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span>专业选修</span>
                    <div className="flex items-center gap-2">
                      <Badge variant="secondary">702门</Badge>
                      <span className="text-sm text-muted-foreground">(30%)</span>
                    </div>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span>通识选修</span>
                    <div className="flex items-center gap-2">
                      <Badge variant="outline">234门</Badge>
                      <span className="text-sm text-muted-foreground">(10%)</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="enrollment" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <TrendingUp className="mr-2 h-5 w-5" />
                招生与课程开设趋势
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                {/* Trend Chart Placeholder */}
                <div className="h-64 bg-gray-50 rounded-lg flex items-center justify-center">
                  <div className="text-center text-gray-500">
                    <BarChart3 className="mx-auto h-12 w-12 mb-2" />
                    <p>招生趋势图表</p>
                    <p className="text-sm">显示历年学生数量和课程开设情况</p>
                  </div>
                </div>
                
                {/* Trend Data Table */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <h4 className="font-medium mb-3">学期数据对比</h4>
                    <div className="space-y-2">
                      {enrollmentTrend.slice(-4).map((item, index) => (
                        <div key={index} className="flex justify-between items-center p-2 border rounded">
                          <span className="text-sm">{item.semester}</span>
                          <div className="text-right">
                            <div className="text-sm font-medium">{item.students.toLocaleString()}人</div>
                            <div className="text-xs text-muted-foreground">{item.courses}门课程</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                  
                  <div>
                    <h4 className="font-medium mb-3">增长率分析</h4>
                    <div className="space-y-3">
                      <div className="p-3 bg-blue-50 rounded-lg">
                        <div className="flex justify-between items-center">
                          <span className="text-sm">学生增长率</span>
                          <span className="text-lg font-medium text-blue-600">+2.5%</span>
                        </div>
                        <p className="text-xs text-blue-700 mt-1">较上学期增长312人</p>
                      </div>
                      
                      <div className="p-3 bg-green-50 rounded-lg">
                        <div className="flex justify-between items-center">
                          <span className="text-sm">课程增长率</span>
                          <span className="text-lg font-medium text-green-600">+1.8%</span>
                        </div>
                        <p className="text-xs text-green-700 mt-1">较上学期新增41门课程</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="academic" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Grade Distribution */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center">
                  <BarChart3 className="mr-2 h-5 w-5" />
                  成绩分布统计
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {gradeDistribution.map((item, index) => (
                    <div key={index} className="space-y-2">
                      <div className="flex justify-between items-center">
                        <span className="text-sm font-medium">等级 {item.grade}</span>
                        <span className="text-sm">{item.count.toLocaleString()}人 ({item.percentage}%)</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div 
                          className={`h-2 rounded-full ${
                            index === 0 ? 'bg-green-600' :
                            index === 1 ? 'bg-blue-600' :
                            index === 2 ? 'bg-orange-600' :
                            index === 3 ? 'bg-yellow-600' :
                            'bg-red-600'
                          }`}
                          style={{ width: `${item.percentage}%` }}
                        ></div>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* Academic Performance */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center">
                  <Calendar className="mr-2 h-5 w-5" />
                  学术表现指标
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="p-3 border rounded-lg">
                    <div className="flex justify-between items-center mb-2">
                      <span className="text-sm font-medium">平均绩点</span>
                      <span className="text-lg font-medium text-blue-600">3.45</span>
                    </div>
                    <div className="text-xs text-muted-foreground">
                      较上学期提升0.12
                    </div>
                  </div>
                  
                  <div className="p-3 border rounded-lg">
                    <div className="flex justify-between items-center mb-2">
                      <span className="text-sm font-medium">及格率</span>
                      <span className="text-lg font-medium text-green-600">94.8%</span>
                    </div>
                    <div className="text-xs text-muted-foreground">
                      共18,776人次及格
                    </div>
                  </div>
                  
                  <div className="p-3 border rounded-lg">
                    <div className="flex justify-between items-center mb-2">
                      <span className="text-sm font-medium">优秀率</span>
                      <span className="text-lg font-medium text-orange-600">28.5%</span>
                    </div>
                    <div className="text-xs text-muted-foreground">
                      共5,632人次获得A等级
                    </div>
                  </div>
                  
                  <div className="p-3 border rounded-lg">
                    <div className="flex justify-between items-center mb-2">
                      <span className="text-sm font-medium">平均出勤率</span>
                      <span className="text-lg font-medium text-purple-600">96.3%</span>
                    </div>
                    <div className="text-xs text-muted-foreground">
                      全校整体出勤情况良好
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="department" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <Users className="mr-2 h-5 w-5" />
                院系数据对比
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left py-3 px-4">院系名称</th>
                      <th className="text-center py-3 px-4">学生数</th>
                      <th className="text-center py-3 px-4">教师数</th>
                      <th className="text-center py-3 px-4">课程数</th>
                      <th className="text-center py-3 px-4">平均分</th>
                      <th className="text-center py-3 px-4">出勤率</th>
                    </tr>
                  </thead>
                  <tbody>
                    {departmentStats.map((dept, index) => (
                      <tr key={index} className="border-b hover:bg-gray-50">
                        <td className="py-3 px-4 font-medium">{dept.name}</td>
                        <td className="py-3 px-4 text-center">{dept.students.toLocaleString()}</td>
                        <td className="py-3 px-4 text-center">{dept.teachers}</td>
                        <td className="py-3 px-4 text-center">{dept.courses}</td>
                        <td className="py-3 px-4 text-center">
                          <span className={`font-medium ${
                            dept.avgScore >= 88 ? 'text-green-600' :
                            dept.avgScore >= 85 ? 'text-blue-600' :
                            'text-orange-600'
                          }`}>
                            {dept.avgScore}
                          </span>
                        </td>
                        <td className="py-3 px-4 text-center">
                          <span className={`font-medium ${
                            dept.attendanceRate >= 97 ? 'text-green-600' :
                            dept.attendanceRate >= 95 ? 'text-blue-600' :
                            'text-orange-600'
                          }`}>
                            {dept.attendanceRate}%
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}